package com.rjwh.dingdong.client.activity.mathgame;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.widget.ListView;

import com.aishua.lib.utils.AsStrUtils;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.activity.webbrowser.OaGameActivity;
import com.rjwh.dingdong.client.adapter.MathGameBookIslandGameAdapter;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.bean.localbean.BookIslandGameBean;
import com.rjwh.dingdong.client.bean.localbean.LocalGmaeInfo;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.mvp.presenter.impl.MathGameIslandsListPresenter;
import com.rjwh.dingdong.client.mvp.view.MathGameIslandsListView;
import com.rjwh.dingdong.client.service.HttpWebCoreService;
import com.rjwh.dingdong.client.service.PlaybackService;
import com.rjwh.dingdong.client.util.FileUtils;
import com.rjwh.dingdong.client.util.ToastUtil;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author Kay
 * @ClassName MathGameIslandsListActivity
 * @Description 岛的游戏目录
 * @date 2016-8-30
 * @history 2016-8-30 author: description:
 */
public class MathGameIslandsListActivity extends BaseActivity implements MathGameIslandsListView, MathGameBookIslandGameAdapter.OnItemButtonClickListener {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.math_game_island_list_lv)
    ListView mathGameIslangListLv;
    @BindView(R.id.math_game_island_list_mPullRefreshView)
    SwipyRefreshLayout mathGameIslandListMPullRefreshView;

    private int pageNumber;
    private int bookid;
    private MathGameIslandsListPresenter presenter;
    private MathGameBookIslandGameAdapter adapter;
    private String bookname;
    private String tag;
    private String version = "";
    private PlaybackService mPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.math_game_island_list_layout);
        ButterKnife.bind(this);
        parseIntent();
        initView();
        presenter = new MathGameIslandsListPresenter(this, this);
        presenter.subscribe();
        mathGameIslandListMPullRefreshView.doPullRefreshing();
    }

    public static void startActivity(Context context, int bookid, String bookname, String tag) {
        Intent intent = new Intent(context, MathGameIslandsListActivity.class);
        intent.putExtra("bookid", bookid);
        intent.putExtra("bookname", bookname);
        intent.putExtra("tag", tag);
        context.startActivity(intent);
    }

    private void parseIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            bookid = intent.getIntExtra("bookid", 0);
            bookname = intent.getStringExtra("bookname");
            tag = intent.getStringExtra("tag");
        }
        List<LocalGmaeInfo> localGmaeInfoList = MyApplication.db.findAllByWhere(LocalGmaeInfo.class, "pid=" + bookid + " and type=2");
        if (!localGmaeInfoList.isEmpty()) {
            LocalGmaeInfo localGmaeInfo = localGmaeInfoList.get(0);
            if (localGmaeInfo.getVersion() != null) {
                version = localGmaeInfo.getVersion();
            }
        }
    }

    private void initView() {
        initToolbarHelper();
        mathGameIslandListMPullRefreshView.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(SwipyRefreshLayoutDirection direction) {
                switch (direction) {
                    case TOP:
                        pageNumber = 0;
                        doGetBookIslandGame(true, SwipyRefreshLayoutDirection.TOP);
                        break;
                    case BOTTOM:
                        pageNumber++;
                        doGetBookIslandGame(false, SwipyRefreshLayoutDirection.BOTTOM);
                        break;

                    default:
                        break;
                }
            }
        });
        adapter = new MathGameBookIslandGameAdapter(this, this);
        mathGameIslangListLv.setAdapter(adapter);
    }

    private void doGetBookIslandGame(boolean isRefresh, SwipyRefreshLayoutDirection direction) {
        presenter.doGetBookIslandGame(bookid, version, pageNumber, isRefresh, direction);
    }

    protected void initToolbarHelper() {
        toolbar.setTitle("");
        this.setSupportActionBar(this.toolbar);
        if (getSupportActionBar() != null) {
            if (!AsStrUtils.isEmpty(bookname)) {
                getSupportActionBar().setTitle(bookname);
            } else {
                getSupportActionBar().setTitle("精品游戏");
            }
        }
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    @Override
    public void setDirection(SwipyRefreshLayoutDirection direction) {
        mathGameIslandListMPullRefreshView.setDirection(direction);
    }

    @Override
    public void setRefreshing(boolean refreshing) {
        mathGameIslandListMPullRefreshView.setRefreshing(refreshing);
    }

    @Override
    public void loadData(boolean isRefresh, List<BookIslandGameBean> gamelist) {
        if (isRefresh) {
            adapter.clearAll();
        }
        adapter.appendToList(gamelist);
    }

    @Override
    public void onPlaybackServiceBound(PlaybackService mPlaybackService) {
        mPlayer = mPlaybackService;
    }

    @Override
    public void onPlaybackServiceUnbound() {
        mPlayer = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.detachView();
    }

    @Override
    public void onItemButtonClick(String bookid, String lessonid, String gamedir, String gameid) {
        if (isGameNotNull(bookid)) {
            if (AsStrUtils.isEmpty(bookid) || AsStrUtils.isEmpty(lessonid) || AsStrUtils.isEmpty(gamedir) || AsStrUtils.isEmpty(gameid)) {
                ToastUtil.showToast(this, getString(R.string.game_not_existed));
                return;
            }
            File file = new File(FileUtils.getGameDirectory(), bookid + "/" + gamedir);
            if (file.isDirectory() && file.listFiles().length > 0) {
                String userid = MyApplication.spUtil.getStrPreferenceByParamName(this, LocalConstant.SP_USERID);
                String babyid = MyApplication.spUtil.getStrPreferenceByParamName(this, LocalConstant.SP_BABYID);
                String token = MyApplication.spUtil.getStrPreferenceByParamName(this, LocalConstant.SP_USER_TOKEN);
                String uuid = MyApplication.deviceId;
                String version = MyApplication.versionCode;
                String url = String.format(HttpWebCoreService.GAME_ITEM_URL, bookid, gamedir, userid,
                        babyid, version, uuid, token, System.currentTimeMillis(), bookid, lessonid, gamedir, gameid);
                OaGameActivity.startActivity(this, url);
                if (mPlayer != null && mPlayer.isPlaying()) {
                    mPlayer.pause();
                }
            } else {
                ToastUtil.showToast(this, getString(R.string.game_filepath_error));
            }
        } else {
            // 进入游戏详情弹框
            showGoToGameDetialDialog(bookid);
        }
    }

    private void showGoToGameDetialDialog(final String bookid) {
        new AlertDialog.Builder(this)
                .setMessage(getString(R.string.dialog_mes_not_find_game_on_phone))
                .setPositiveButton(getString(R.string.dialog_to_download), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (!AsStrUtils.isEmpty(tag) && tag.equals("MathGameDetailActivity")) {
                            //如果从游戏详情进入的游戏列表,则返回到详情去下载
                            finish();
                        } else {
                            //如果是从首页进入的游戏列表,则跳转到详情去下载
                            MathGameDetailActivity.startActivity(MathGameIslandsListActivity.this, bookid);
                        }
                    }
                })
                .setNegativeButton(getString(R.string.dialog_do_it_later), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }

    private boolean isGameNotNull(String bookid) {
        boolean result = false;
        List<LocalGmaeInfo> localGmaeInfoList = MyApplication.db.findAllByWhere(LocalGmaeInfo.class, "pid=" + bookid + " and type=2");
        if (!localGmaeInfoList.isEmpty()) {
            result = true;
        }
        return result;
    }

}
